package org.jiajie.coffeecodes.condition;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jie
 * @date 2021/8/23 9:45 PM
 */
public class TaskQueue {
    private final Lock lock = new ReentrantLock();
    // 引用的Condition对象必须从Lock实例的newCondition()返回，
    // 这样才能获得一个绑定了Lock实例的Condition实例。
    private final Condition condition = lock.newCondition();
    private Queue<String> queue = new LinkedList<>();

    public void addTask(String s){
        lock.lock();
        try {
            queue.add(s);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public String getTask() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()){
                condition.await();
            }
            return queue.remove();
        } finally {
            lock.unlock();
        }
    }
}
